package com.night.xjh.controller;

import com.night.common.entity.ResultVo;
import com.night.common.entity.StatusCode;

import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.nio.file.AccessDeniedException;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: GlobalAdvisor
 * @Description: //TODO
 * @author: xjh
 * @date: 2022/10/24-10:26
 * @version: v1.0
 */
@RestControllerAdvice(basePackages = "com.night.xjh.controller")
public class GlobalAdvisor {
    @ExceptionHandler
    public ResultVo<String> exceptionHandler(Exception e) {
        e.printStackTrace();
        return new ResultVo<>(StatusCode.ERROR.code, StatusCode.ERROR.msg);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResultVo<Map<String, String>> handlerMethodArgumentNotValidException(BindException exception) {
        Map<String, String> map = new HashMap<>();
        exception.getFieldErrors().forEach(e -> map.put(e.getField(), e.getDefaultMessage()));
        return new ResultVo<>(StatusCode.VALUE_FAIL.code, StatusCode.VALUE_FAIL.msg, map);
    }

    @ExceptionHandler(ConstraintViolationException.class)
    public ResultVo<Map<String, String>> handlerConstraintViolationException(ConstraintViolationException exception) {
        Map<String, String> map = new HashMap<>();
        exception.getConstraintViolations().forEach(e -> map.put(e.getPropertyPath().toString(), e.getMessage()));
        return new ResultVo<>(StatusCode.VALUE_FAIL.code, StatusCode.VALUE_FAIL.msg, map);
    }

    @ExceptionHandler(AccessDeniedException.class)
    public ResultVo<?> handlerAccessDeniedException(AccessDeniedException exception) {
        return new ResultVo<>(StatusCode.NO_PERM);
    }
//
//    @ExceptionHandler(ValidateException.class)
//    public ResultVo<?> handlerValidateException(ValidateException exception) {
//        return new ResultVo<>(StatusCode.CAPTCHA_FAIL);
//    }
}
